package com.djl.sqtg.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;


public class TencentCOSUtil {

    // 指定文件将要存放的存储桶
    private static String bucketName = "djl-1314040106";
    // 上文获得的SecretId
    private static String secretId = "AKIDSkmY4LM8euue8MK2UgcIismQTHq9CzWn";
    // 上文获得的SecretKey
    private static String secretKey = "3qMddNr55qMccNs76pIVR7XhaEclfIn2";
    private static COSClient cosClient;
    static {
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2.1 设置存储桶的地域（上文获得）
        Region region = new Region("ap-chengdu");
        ClientConfig clientConfig = new ClientConfig(region);
        // 2.2 使用https协议传输
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
         cosClient = new COSClient(cred, clientConfig);
    }

    public static String UploadIMG(MultipartFile imgFile,String directory) {
        try {
            InputStream inputStream = imgFile.getInputStream();
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // - 使用输入流存储，需要设置请求长度
            objectMetadata.setContentLength(inputStream.available());
            // - 设置缓存
            objectMetadata.setCacheControl("no-cache");
            // - 设置Content-Type
            objectMetadata.setContentType(imgFile.getContentType());
            // 指定文件将要存放的存储桶
            //String bucketName = "djl-1314040106";
            // 指定文件上传到 COS 上的路径，即对象键。
            String key = directory+"/" + imgFile.getOriginalFilename();
            System.out.println("key------>"+key);
            PutObjectResult putResult = cosClient.putObject(bucketName, key,inputStream, objectMetadata);
            // 成功存储后，返回图片url
//            return putResult.getContentMd5();
            String url = "https://djl-1314040106.cos.ap-chengdu.myqcloud.com/"+key;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            // 发生IO异常、COS连接异常等，返回空
            return null;
        }
    }
}
